/* global window */

import { history } from 'umi';
import { stringify } from 'qs';

const { pathToRegexp } = require('path-to-regexp');
import { queryLayout } from 'utils';
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant';
import config from 'config';
import { menuList } from 'utils/menuList';
import storageUtils from 'utils/storage';
import { message } from 'antd';
import { loginApi } from 'api/index';

const goHome = () => {
    if (pathToRegexp(['/', '/login']).exec(window.location.pathname)) {
        history.push({
            pathname: '/home',
        });
    }
};

export default {
    namespace: 'app',
    state: {
        // 根路径
        routeList: [
            {
                id: '000',
                icon: 'home',
                name: 'Home',
                zhName: '我的页面',
                router: '/home',
            },
        ],
        // 记录当前url信息
        locationPathname: '',
        // 记录退出前最后一次的url 方便下次登录直接定位
        locationQuery: {},
        theme: storageUtils.getTheme() || 'dark',
        collapsed: storageUtils.getCollapsed() || false,
        notifications: [
            {
                title: 'New User is registered.',
                date: new Date(Date.now() - 10000000),
            },
            {
                title: 'Application has been approved.',
                date: new Date(Date.now() - 50000000),
            },
        ],
    },
    reducers: {
        updateState(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
        handleThemeChange(state, { payload }) {
            storageUtils.saveTheme(payload);
            state.theme = payload;
        },
        handleCollapseChange(state, { payload }) {
            storageUtils.saveCollapsed(payload);
            state.collapsed = payload;
        },
        allNotificationsRead(state) {
            state.notifications = [];
        },
    },
    effects: {
        * login({ payload }, { put, call, select }) {
            // 登录
            const data = yield call(loginApi, payload);
            if (data.status === 'success') {
                storageUtils.saveIsLogin(true);
                const { locationQuery } = yield select(_ => _.app);
                const { from } = locationQuery;
                const isInit = storageUtils.getIsInit();
                if (isInit) {
                    goHome();
                    return;
                }
                const { locationPathname } = yield select(_ => _.app);
                const resultData = data.result;
                const permissions = { visit: resultData.menuNo };
                // const permissions = {
                //     visit: [
                //         '000',
                //         '001', '0011', '0012', '0013', '0014', '0015', '0016',
                //         '002', '0021', '0022', '0023', '0024', '0025', '0026', '0027',
                //         '003', '0031', '0032', '0033', '0034', '00311', '00312',
                //         '004', '0041',
                //         '005',
                //         '006', '0061', '0062', '0063',
                //         '007', '0071', '0072', '0073',
                //         '008',
                //     ],
                // };

                if (resultData) {
                    let routeList = menuList;
                    routeList = menuList.filter(item => {
                        const cases = [
                            permissions.visit.includes(item.id),
                            item.mpid
                                ? permissions.visit.includes(item.mpid) || item.mpid === '-1'
                                : true,
                            item.bpid ? permissions.visit.includes(item.bpid) : true,
                        ];
                        return cases.every(_ => _);
                    });
                    storageUtils.saveRouteList(routeList);
                    storageUtils.savePermissions(permissions);
                    storageUtils.saveUser({
                        realName: resultData.realName,
                        loginId: resultData.loginId,
                        credentialsNo: resultData.credentialsNo,
                        userRoleTypes: resultData.userRoleTypes,
                    });
                    storageUtils.saveIsInit(true);
                    storageUtils.saveToken(resultData.accessToken);
                    goHome();
                } else if (queryLayout(config.layouts, locationPathname) !== 'public') {
                    history.push({
                        pathname: '/login',
                        search: stringify({
                            from: locationPathname,
                        }),
                    });
                }

                if (!pathToRegexp('/login').exec(from)) {
                    if (['', '/'].includes(from)) {
                        history.push('/home');
                    } else {
                        history.push(from);
                    }
                } else {
                    history.push('/home');
                }
            } else {
                message.warning(data.message);
            }
        },

        * signOut({ payload }, { call, put }) {
            storageUtils.saveRouteList([]);
            storageUtils.savePermissions({ visit: [] });
            storageUtils.saveUser({});
            storageUtils.saveIsInit(false);
            storageUtils.saveIsLogin(false);
            storageUtils.saveToken({});
            history.push('/login');
        },
    },
    subscriptions: {
        setup({ dispatch }) {
            // 是否登录
            const isLogin = storageUtils.getIslogin();
            if (!isLogin) {
                history.push({
                    pathname: '/login',
                });
            } else {
            }
        },
        setupHistory({ dispatch, history }) {
            history.listen(location => {
                dispatch({
                    type: 'updateState',
                    payload: {
                        locationPathname: location.pathname,
                        locationQuery: location.query,
                    },
                });
            });
        },

        setupRequestCancel({ history }) {
            history.listen(() => {
                const { cancelRequest = new Map() } = window;
                cancelRequest.forEach((value, key) => {
                    if (value.pathname !== window.location.pathname) {
                        value.cancel(CANCEL_REQUEST_MESSAGE);
                        cancelRequest.delete(key);
                    }
                });
            });
        },
    },

};
